<!--
  支付配置组件：  1. 参数费率的填写， 2.支付通道的选择

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/04/06 10:14
-->
<template>
  <a-tabs v-model:activeKey="vdata.topTabsVal" tabBarStyle="padding-left:40vw" tabPosition="top">
    <a-tab-pane v-if="tabIsShow('paramsAndRateTab')" key="paramsAndRateTab" tab="参数及费率的填写">
      <div class="search">
        <a-input v-model:value="vdata.ifCodeListSearchData.ifName" class="rate-input" placeholder="搜索渠道名称" />
        <a-input v-model:value="vdata.ifCodeListSearchData.ifCode" class="rate-input" placeholder="搜索渠道代码" />
        <a-button type="primary" :loading="vdata.btnLoading" @click="searchFunc">
          <template #icon><search-outlined /></template>查询
        </a-button>
        <a-button style="margin-left: 8px" @click="() => (vdata.ifCodeListSearchData = {})"><reload-outlined />重置</a-button>
      </div>
      <!-- 支付渠道 start -->
      <div class="pay-list-wrapper" :style="{ height: vdata.rateListHeight }">
        <div v-for="(v, i) in vdata.ifCodeList" :key="i" class="pay-item-wrapper">
          <div class="pay-content" :class="{ 'pay-selected': vdata.currentIfCode == v.ifCode }" :style="v.stateBgColor" @click="selectIfCode(v.ifCode)">
            <div class="pay-img" :style="{ backgroundColor: v.bgColor }">
              <img :src="v.icon" alt="">
              <div class="pay-state-dot" :style="{ backgroundColor: calcStateBgColor(v.configState) }" />
            </div>
            <div class="pay-info">
              <div class="pay-title">{{ v.ifName }}</div>
              <div class="pay-code">{{ v.ifCode }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 支付渠道end -->

      <template v-if="vdata.currentIfCode">
        <!-- tab 选择框部分 start -->
        <div class="tab-wrapper">
          <div class="tab-content">
            <a-dropdown v-if="tabIsShow('paramsTab')" :trigger="['contextmenu']">
              <template #overlay>
                <a-menu v-if="isShowPasteBtn('paramsVal') || isShowCopyBtn('paramsVal')">
                  <a-menu-item v-if="isShowPasteBtn('paramsVal')" key="2" @click="pasteParamsAndRateFunc('paramsVal')">粘贴[已复制参数]到当前页面</a-menu-item>
                  <a-menu-item v-if="isShowCopyBtn('paramsVal')" key="1" @click="queryRealPayParamsAndCopyFunc()">复制参数和费率</a-menu-item>
                </a-menu>
              </template>

              <div v-if="tabIsShow('paramsTab')" class="tab-item" :class="{ 'tab-selected': vdata.paramsAndRateTabVal == 'paramsTab' }" @click="vdata.paramsAndRateTabVal = 'paramsTab'">
                参数配置
              </div>
            </a-dropdown>

            <a-dropdown v-if="tabIsShow('rateTab')" :trigger="['contextmenu']">
              <template #overlay>
                <a-menu v-if="isShowPasteBtn('rateVal') || isShowCopyBtn('rateVal')">
                  <a-menu-item v-if="isShowPasteBtn('rateVal')" key="22" @click="pasteParamsAndRateFunc('rateVal')">粘贴[已复制费率]到当前页面</a-menu-item>
                  <a-menu-item v-if="isShowCopyBtn('rateVal')" key="11" @click="queryRealPayParamsAndCopyFunc()">复制参数和费率</a-menu-item>
                </a-menu>
              </template>

              <div v-if="tabIsShow('rateTab')" class="tab-item" :class="{ 'tab-selected': vdata.paramsAndRateTabVal == 'rateTab' }" @click="vdata.paramsAndRateTabVal = 'rateTab'">
                费率配置
              </div>
            </a-dropdown>

          
            <div v-if="tabIsShow('channelConfigTab')" class="tab-item" :class="{ 'tab-selected': vdata.paramsAndRateTabVal == 'channelConfigTab' }" @click="vdata.paramsAndRateTabVal = 'channelConfigTab'">渠道配置</div>
            <!-- 下面这个activityConfigTab，单独给平台服务商使用 -->
            <div v-if="tabIsShow('activityConfigTab')" class="tab-item" :class="{ 'tab-selected': vdata.paramsAndRateTabVal == 'activityConfigTab' }" @click="vdata.paramsAndRateTabVal = 'activityConfigTab'">渠道配置</div>
          </div>
          <div class="open-close" @click="openHandle">
            {{ vdata.rateListHeight == '110px' ? '展开' : '收起' }} &nbsp; <down-outlined v-if="vdata.rateListHeight == '110px'" class="arrow" />
            <up-outlined v-else class="arrow" />
          </div>
        </div>
        <div class="content-box">
          <JeepayPayParamsConfigPanel v-if="vdata.paramsAndRateTabVal == 'paramsTab'" ref="jeepayPayParamsConfigPanelRef" :configMode="props.configMode" :infoId="props.infoId" :selectIfCode="vdata.currentIfCode" />
          <JeepayPaywayRatePanel v-if="vdata.paramsAndRateTabVal == 'rateTab'" ref="jeepayPaywayRatePanelRef" :configMode="props.configMode" :infoId="props.infoId" :selectIfCode="vdata.currentIfCode" />
          <!-- 渠道配置 -->
          <JeepayAppChannelConfigInnerDiv v-if="vdata.paramsAndRateTabVal == 'channelConfigTab'" :infoId="props.infoId" :configMode="props.configMode" :ifCode="vdata.currentIfCode" />
          <!-- 服务商渠道配置：活动报名配置 -->
          <JeepayActivityConfigPanel v-if="vdata.paramsAndRateTabVal == 'activityConfigTab'" :infoId="props.infoId" :configMode="props.configMode" :ifCode="vdata.currentIfCode" />
        </div>
      </template>
    </a-tab-pane>
    <a-tab-pane v-if="tabIsShow('mchPassageTab')" key="mchPassageTab" tab="支付渠道的选择">
      <div class="content-box">
        <JeepayMchPassageConfigPanel :configMode="props.configMode" :infoId="props.infoId" />
      </div>
    </a-tab-pane>
  </a-tabs>
</template>

<script lang="ts" setup>
import { $getPayConfigIfcodes, $getInterfaceSavedConfigs, $getRateConfigSavedMapData, $getAgentConfig } from '@/api/manage'
import { reactive, onMounted, nextTick, ref, inject, getCurrentInstance } from 'vue'
import JeepayPaywayRatePanel from '../JeepayRateFeeConfig/JeepayPaywayRatePanel.vue'
import { Base64 } from 'js-base64'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
import { getOriginIfCode } from '../util/jeepayComponentUtil.js'

// 是否是特约商户 
let configMchAppIsIsvsubMch : any = inject('configMchAppIsIsvsubMch')

const jeepayPayParamsConfigPanelRef = ref()
const jeepayPaywayRatePanelRef = ref()

// 定义父组件的传值
const props: any = defineProps({
  infoId: { type: String, default: '' }, // 当前配置的所属infoId
  configMode: { type: String, default: '' }, // 模式
})

// 定义响应式数据
const vdata: any = reactive({
  ifCodeListSearchData: { ifName: '' }, // 支付渠道列表的搜索条件
  ifCodeList: [], //当前服务商的支持接口列表
  currentIfCode: '', //当前选择的支付通道
  checked: true, // 单选框默认打开
  uncheck: false, // 单选默认关闭
  number: 2, // 当大于此值时，将展示展开与收起按钮
  rateListHeight: 'auto', // 初始高度
  topTabsVal: 'paramsAndRateTab', //顶部选择项目的当前选择值， paramsAndRateTab  /  mchPassageTab
  paramsAndRateTabVal: 'paramsTab', // 参数及费率卡片的内部切换  paramsTab / rateTab
  copiedData: { ifCode: '', configMode: '', paramsVal: '', rateVal: '' }, //被复制的数据
  agentSubMchWxConfigCanUse: false
})

// 动态获取window可视区域宽度
let initialWidth = document.body.clientWidth

window.addEventListener('resize', () => {
  initialWidth = document.body.clientWidth
  dynamicWidth(initialWidth)
})

// 根据不同的宽度动态为 vdata.number 赋值
const dynamicWidth = (initialWidth) => {
  if (initialWidth >= 1600) {
    vdata.number = 7
  } else if (initialWidth >= 1366) {
    vdata.number = 5
  } else if (initialWidth >= 1024) {
    vdata.number = 4
  } else {
    vdata.number = 2
  }
}
dynamicWidth(initialWidth)

// 定义文字颜色
const stateColor = (state) => {
  if (typeof state == 'undefined') {
    return '#949494'
  } else if (state == 1) {
    return '#1890ff'
  } else {
    return '#ff0000'
  }
}

// 展开与收起
const openHandle = () => {
  const payIndex = vdata.ifCodeList.findIndex((v) => v.ifCode == vdata.currentIfCode)
  const filterArray = vdata.ifCodeList.filter((v) => v.ifCode == vdata.currentIfCode)
  if (filterArray.length >= 2 && vdata.ifCodeList[0].ifCode == vdata.currentIfCode) {
    vdata.ifCodeList.shift()
    return (vdata.rateListHeight = 'auto')
  }
  if (payIndex >= 5) {
    vdata.ifCodeList.unshift(vdata.ifCodeList[payIndex])
  }
  vdata.rateListHeight == '110px' ? (vdata.rateListHeight = 'auto') : (vdata.rateListHeight = '110px')
}

// 搜索渠道名称
const searchFunc = () => {
  getShowIfCodeList()
}

// 查询支持的接口
const getShowIfCodeList = () => {
  vdata.btnLoading = true

  $getPayConfigIfcodes(props.infoId, props.configMode, vdata.ifCodeListSearchData.ifName)
    .then((res) => {
      vdata.ifCodeList = res
      vdata.currentIfCode = props.selectIfCode // 默认接口
      vdata.btnLoading = false
    })
    .catch(() => (vdata.btnLoading = false))
}

// 挂载钩子函数
onMounted(() => {
  vdata.currentIfCode = '' // 默认不选中

  // 查询 【支持的支付接口】
  getShowIfCodeList()

  // 当有禁用的， 那么默认选中第二个
  if (!tabIsShow('paramsTab') && tabIsShow('rateTab')) {
    vdata.paramsAndRateTabVal = 'rateTab'
  }

  // 特约商户配置信息
  if (props.configMode == 'mchSelfApp2') {
    vdata.topTabsVal = 'mchPassageTab'
  }

  if (props.configMode == 'agentMch') {
    queryAgentConfig()
  }

})

// 代理商配置
function queryAgentConfig() {
  $getAgentConfig('subMchWxConfigIsUsable').then(config => {
    if (config && config.configVal) {
      vdata.agentSubMchWxConfigCanUse = config.configVal=='true'?true:false
    }
  })
}

// 切换 【支付产品】
function selectIfCode(ifCode) {
  vdata.currentIfCode = ''
  nextTick(() => (vdata.currentIfCode = ifCode))
}

// 判断是否显示支付接口的状态
function showIfCodeState() {

  if(props.configMode == 'mgrIsv' || props.configMode == 'mgrAgent' || props.configMode == 'mgrMch' || props.configMode == 'agentMch' || props.configMode == 'agentSelf' || props.configMode == 'agentSubagent' || props.configMode == 'mchSelfApp1'){
    return true
  }

  return false
}

// 判断tab是否需要显示的列
// paramsTab 参数配置          rateTab  费率配置    channelConfigTab  渠道配置  activityConfigTab 服务商渠道配置
// mchPassageTab  支付渠道选择
// paramsAndRateTab  参数及费率填写 
function tabIsShow(currentTabVal) {
  let disableArr: any = []
  // 配置服务商  禁用支付渠道选择
  if (props.configMode == 'mgrIsv') {
    disableArr = ['mchPassageTab', 'channelConfigTab']
  }

  // 配置服务商  禁用支付渠道选择
  if (props.configMode == 'mgrAgent') {
    disableArr = ['mchPassageTab', 'channelConfigTab', 'activityConfigTab']
  }

  // 代理商配置自己的页面
  if (props.configMode == 'agentSelf') {
    disableArr = ['mchPassageTab', 'paramsTab', 'channelConfigTab', 'activityConfigTab']
  }

  // 代理商下级代理商
  if (props.configMode == 'agentSubagent') {
    disableArr = ['mchPassageTab', 'channelConfigTab', 'activityConfigTab']
  }

  // 特约商户配置信息
  if (props.configMode == 'mchSelfApp2') {
    disableArr = ['paramsAndRateTab', 'rateTab', 'paramsTab', 'channelConfigTab', 'activityConfigTab']
  }

  // 普通商户配置信息
  if (props.configMode == 'mchSelfApp1') {
    disableArr = ['channelConfigTab', 'activityConfigTab']
  }

  // 配置信息 运营配置商户 
  if (props.configMode == 'mgrMch') {
    disableArr = ['activityConfigTab']

    // 允许显示
    if(configMchAppIsIsvsubMch && configMchAppIsIsvsubMch.value){
      console.log('显示渠道配置')

    }else{ // 不允许显示

      disableArr = ['channelConfigTab', 'activityConfigTab']
    }
    
  }

  // 代理商不允许配置
  if (props.configMode == 'agentMch') {
    // 权限可用放开tab，可配置微信参数
    if (!vdata.agentSubMchWxConfigCanUse) {
        disableArr = ['channelConfigTab']
    }
  }


  return disableArr.indexOf(currentTabVal) < 0
}
// 计算 状态颜色
const calcStateBgColor = (state) => {
  if (!state) return '#D9D9D9'
  return state == 1 ? '#29CC96' : '#EC2E2E'
}


// 是否显示： 复制参数按钮
function isShowCopyBtn(dataType){

  if(dataType == 'paramsVal' && vdata.paramsAndRateTabVal != 'paramsTab'){
    return false
  }

  if(dataType == 'rateVal' && vdata.paramsAndRateTabVal != 'rateTab'){
    return false
  }

  // 只有： 运营平台配置服务商、 运营平台配置代理商 ， 运营配置商户 需要该复制选项
  if(props.configMode == 'mgrIsv' || props.configMode == 'mgrAgent' || props.configMode == 'mgrMch'){
    return true
  }
  return false

}


// 是否显示： 粘贴参数， 粘贴费率
// ifCodeItem 列表中的ifCode 
// dataType paramsVal 和 rateVal
function isShowPasteBtn(dataType){

  // 如果复制没有权限， 那么粘贴也没必要显示了。 
  if(!isShowCopyBtn(dataType)){
    return false
  }

  // 不包含数据时
  if(!vdata.copiedData || !vdata.copiedData.ifCode){
    return false
  }

  // 选择的是同一个接口时
  if(vdata.copiedData.ifCode == vdata.currentIfCode){
    return false
  }

  // 选择是不是同一套支付接口时（ 仅克隆接口需要 ）
  if(getOriginIfCode(vdata.copiedData.ifCode) != getOriginIfCode(vdata.currentIfCode)){
    return false
  }

  // 支付参数 || 费率参数 为空
  if(!vdata.copiedData[dataType]){
    return false
  }

  // 场景不同， 不允许复制
  if(vdata.copiedData.configMode != props.configMode){
    return false
  }

  return true

}


// 复制参数 和 费率，  查询真实的参数及费率（ 然后保持到本地 ）
async function queryRealPayParamsAndCopyFunc(){

  // 初始化
  vdata.copiedData = { ifCode: vdata.currentIfCode, configMode: props.configMode, paramsVal: '', rateVal: '' }

  // 查询支付参数
  await $getInterfaceSavedConfigs(props.infoId, vdata.currentIfCode, props.configMode, 1).then(configRes => {

    if(!configRes || !configRes.ifParams){
      $infoBox.message.error('没有配置任何参数！')
      return Promise.reject()
    }

    // parmsVal 是 JSON的string类型， 而不是 Object类型 
    vdata.copiedData.paramsVal = Base64.decode(configRes.ifParams)

  })

  await $getRateConfigSavedMapData(props.infoId, props.configMode, vdata.currentIfCode).then( rateRes => {

    // 费率不涉及敏感数据， 不需要做base64处理
    vdata.copiedData.rateVal = rateRes

  })


  $infoBox.message.success('复制成功')

}

// 粘贴参数到页面选择的接口中去
function pasteParamsAndRateFunc(dataType){

  // 粘贴 参数
  if(dataType == 'paramsVal'){
    jeepayPayParamsConfigPanelRef.value.reloadParamsPageByParse(vdata.copiedData[dataType])
  }

  // 粘贴 费率
  if(dataType == 'rateVal'){
    jeepayPaywayRatePanelRef.value.reloadRateDataPageByParse(vdata.copiedData[dataType])
  }

}


</script>

<style lang="less" scoped>
.search {
  display: flex;
  margin-top: 30px;
  margin-left: 50px;
  .rate-input {
    width: 200px;
    margin-right: 10px;
  }
}
// 支付渠道 卡片部分
.pay-list-wrapper {
  display: flex;
  flex-wrap: wrap;
  padding: 0 40px;
  margin-top: 20px;
  overflow: hidden;
}
.pay-item-wrapper {
  padding: 10px;
  width: 20%;
}
.pay-content {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 90px;
  border-radius: 5px;
  border: 1px solid #dedede;
  background: #fff;
  cursor: pointer;
  .pay-img {
    flex-shrink: 0;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 20px;
    margin-right: 12px;
    background-color: #0853ad;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    img {
      width: 50%;
    }
    .pay-state-dot {
      box-sizing: content-box;
      display: block;
      position: absolute;
      bottom: -3px;
      right: -3px;
      width: 12px;
      height: 12px;
      background-color: var(--state-bg-color);
      border: 3px solid #fff;
      border-radius: 50%;
    }
  }
  .pay-info {
    .pay-title {
      font-size: 14px;
      font-weight: 600;
    }
    .pay-code {
      font-size: 13px;
      color: rgb(26, 25, 25);
    }
  }
}
// 支付渠道卡片选中后的样式
.pay-selected {
  border: 2px solid #1a79ff;
  background: rgba(25, 121, 255, 0.05);
  &::after {
    content: '√';
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 30px;
    height: 30px;
    background-color: #1a79ff;
    color: #fff;
    font-size: 18px;
    font-weight: 700;
    border-radius: 0 0 0 5px;
  }
}
// tab 选择框部分
.tab-wrapper {
  position: relative;
  height: 50px;
  &::after {
    content: '';
    display: block;
    position: absolute;
    top: 50%;
    width: 100%;
    height: 1px;
    background-color: #d9d9d9;
  }
  .open-close {
    width: 80px;
    height: 36px;
    cursor: pointer;
    border-radius: 5px;
    background: #fff;
    border: 1px solid #e8e8e8;
    border-top: none;
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 1;
    margin-left: -40px;
    margin-top: -18px;
    display: flex;
    justify-content: center;
    align-items: center;
    &::after,
    &::before {
      content: '';
      display: block;
      position: absolute;
      top: 0;
      z-index: 10;
      width: 10px;
      height: 18px;
      background-color: #fff;
    }
    &::after {
      left: -1px;
    }
    &::before {
      right: -1px;
    }
  }
}
.tab-content {
  position: relative;
  margin-top: 30px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  z-index: 1;
  margin-left: 50px;
  width: max-content;
  padding: 0 5px;
  height: 50px;
  border-radius: 5px;
  background-color: #f7f7f7;
  border: 1px solid #d9d9d9;
  font-size: 14px;
  color: #808080;
  .tab-item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 119px;
    height: 40px;
    cursor: pointer;
  }
}
.tab-selected {
  color: #000;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
}
// 内容部分
.content-box {
  padding: 0 50px;
}
</style>
